let _Template;
let _View;
let _Model;
let _isView = false;
let _isTemplate = false;
let _isPublish = false;
let _EChartType;
let _ButtonList = new Array();
let _IntervalList = new Array();

$(function () {

    bind();
    search();

    _Model = new loadModel();

    loadMethod();
});

//绑定控件
var bind = function () {

    try {


        _isView = false;
        _isTemplate = false;
        _isPublish = false;

        Template.init("temp_save");
        Template.init("temp_template");
        Template.init("temp_publish");

        $("#div_Modal").draggable();

        document.getElementById("spn_echart_quotavalue").innerHTML = QUOTATITLE;

        OptionUtil.bind("ddl_view_theme", "key", "value", eCharts.theme, false, null, null);
        OptionUtil.bind("ddl_view_backGround", "key", "value", BACKGROUND, false, null, null);
        bindPanel();
        bindView();

        document.getElementById("model_titleColor_0").value = "FFFFFF";
        document.getElementById("model_titleColor_1").value = "FFFFFF";
        document.getElementById("model_titleColor_2").value = "FFFFFF";
        document.getElementById("model_titleBackgroudColor_0").value = "FFFFFF";
        document.getElementById("model_titleBackgroudColor_1").value = "FFFFFF";
        document.getElementById("model_titleBackgroudColor_2").value = "FFFFFF";
        document.getElementById("model_borderColor").value = "FFFFFF";
        document.getElementById("model_backgroudColor").value = "FFFFFF";


        OptionUtil.bind("model_titleStyle", "key", "value", eCharts.style, false, null, null);
        OptionUtil.bind("model_titleWeight", "key", "value", eCharts.weight, false, null, null);
        OptionUtil.bind("model_titlePosition", "key", "value", eCharts.horizontal, false, null, null);

        OptionUtil.bind("echart_titleStyle", "key", "value", eCharts.style, false, null, null);
        OptionUtil.bind("echart_titleWeight", "key", "value", eCharts.weight, false, null, null);

        OptionUtil.bind("echart_bindtype", "key", "value", eCharts.bindType, false, null, null);

        OptionUtil.bind("echart_tooltipTrigger", "key", "value", eCharts.trigger, false, null, null);
        OptionUtil.bind("echart_tooltipPointer", "key", "value", eCharts.indicator, false, null, null);
        OptionUtil.bind("echart_tooltipPosition", "key", "value", eCharts.position, false, null, null);

        OptionUtil.bind("echart_legendOrient", "key", "value", eCharts.orient, false, null, null);

        OptionUtil.bind("echart_axisXType", "key", "value", eCharts.axisType, false, null, null);
        OptionUtil.bind("echart_axisYType", "key", "value", eCharts.axisType, false, null, null);

        OptionUtil.bind("echart_labelPosition", "key", "value", eCharts.position, false, null, null);
        OptionUtil.bind("echart_labelStyle", "key", "value", eCharts.style, false, null, null);
        OptionUtil.bind("echart_labelWeight", "key", "value", eCharts.weight, false, null, null);
        OptionUtil.bind("echart_emphasisPosition", "key", "value", eCharts.position, false, null, null);
        OptionUtil.bind("echart_emphasisStyle", "key", "value", eCharts.style, false, null, null);
        OptionUtil.bind("echart_emphasisWeight", "key", "value", eCharts.weight, false, null, null);

        OptionUtil.bind("echart_colorTheme", "key", "value", eCharts.theme, false, null, null);

        OptionUtil.bind("echart_searchControlExist", "key", "value", eCharts.exist, false, null, null);

        changeBackGround();
    }
    catch (e) {
        alert(e);
    }
}

//查询模板
var search = function () {
    try {
        //获取页面参数
        var vUrlParams = HttpUtil.getUrlParams();

        if (vUrlParams != undefined && vUrlParams != null) {
            let id = vUrlParams.params1;
            let type = vUrlParams.params2;

            if (id != undefined && id != null && type != undefined && type != null && type != "") {
                let xheList = new XheList();
                let code = "";
                let backgroud = "";

                if (type == "view") {
                    code = "viewcode";
                    backgroud = "viewbackground";
                    xheList.model.Table = "t_data_view";
                    xheList.model.SortName = "viewid";
                    xheList.model.Columns = [
                        ["viewid", "视图ID", "15", "", "C", "", true],
                        ["viewname", "视图名称", "15", "", "C", "", true],
                        ["viewremark", "视图描述", "15", "", "C", "", true],
                        ["viewcode", "视图代码", "15", "", "C", "", true],
                        ["viewbackground", "背景图", "15", "", "C", "", true]
                    ];
                    xheList.model.Filter = [
                        ["viewid", "A", "EQ", "I", id]
                    ];
                }
                else if (type == "template") {
                    code = "tempcode";
                    backgroud = "tempbackground";
                    xheList.model.Table = "t_data_template";
                    xheList.model.SortName = "tempid";
                    xheList.model.Columns = [
                        ["tempid", "模板ID", "15", "", "C", "", true],
                        ["tempname", "模板名称", "15", "", "C", "", true],
                        ["tempremark", "模板描述", "15", "", "C", "", true],
                        ["tempcode", "模板代码", "15", "", "C", "", true],
                        ["tempbackground", "背景图", "15", "", "C", "", true]
                    ];
                    xheList.model.Filter = [
                        ["tempid", "A", "EQ", "I", id],
                        ["tempstatus", "A", "EQ", "I", 1]
                    ];
                }
                else if (type == "publish") {
                    code = "publishcode";
                    backgroud = "publishbackground";
                    xheList.model.Table = "t_data_publish";
                    xheList.model.SortName = "publishid";
                    xheList.model.Columns = [
                        ["publishid", "模板ID", "15", "", "C", "", true],
                        ["publishname", "模板名称", "15", "", "C", "", true],
                        ["publishremark", "模板描述", "15", "", "C", "", true],
                        ["publishcode", "模板代码", "15", "", "C", "", true],
                        ["publishbackground", "背景图", "15", "", "C", "", true]
                    ];
                    xheList.model.Filter = [
                        ["publishid", "A", "EQ", "I", id],
                        ["publishstatus", "A", "EQ", "I", 1]
                    ];
                }

                let vResult = xheList.query();

                let vTemplateCode = GZip.decompress(decodeURIComponent(String(vResult.rows[0][code]).replace(/&apos/g, "'")));

                _Template = JSON.parse(vTemplateCode);

                if (type == "view") {
                    $("#txt_PK_Value").val(vResult.rows[0]["viewid"]);
                    $("#txt_viewname").val(vResult.rows[0]["viewname"]);
                    $("#txt_viewname").attr("disabled", true);
                    $("#txt_viewremark").val(vResult.rows[0]["viewremark"]);
                    $("#txt_viewcode").val(vResult.rows[0]["viewcode"]);
                    _isView = true;
                }
                else if (type == "template") {
                    $("#txt_PK_Value").val(vResult.rows[0]["tempid"]);
                    $("#txt_tempname").val(vResult.rows[0]["tempname"]);
                    $("#txt_tempname").attr("disabled", true);
                    $("#txt_tempremark").val(vResult.rows[0]["tempremark"]);
                    $("#txt_tempcode").val(vResult.rows[0]["tempcode"]);
                    _isTemplate = true;
                }
                else if (type == "publish") {
                    $("#txt_PK_Value").val(vResult.rows[0]["publishid"]);
                    $("#txt_publishname").val(vResult.rows[0]["publishname"]);
                    $("#txt_publishname").attr("disabled", true);
                    $("#txt_publishremark").val(vResult.rows[0]["publishremark"]);
                    $("#txt_publishcode").val(vResult.rows[0]["publishcode"]);
                    _isPublish = true;
                }

                if (vResult.rows[0][backgroud] != "") {
                    $("#txt_viewbackground").val(vResult.rows[0][backgroud]);
                    $("#txt_tempbackground").val(vResult.rows[0][backgroud]);
                    $("#txt_publishbackground").val(vResult.rows[0][backgroud]);
                    document.getElementById("div_background").style.backgroundImage = "url(../../common/imgs/" + vResult.rows[0][backgroud] + ")";
                }
            }
        }
    }
    catch (e) {
        alert(e);
    }
}

//事件：应用按钮
function submit() {
    try {
        let vIndex = 0;
        let _model = new xheModel();
        let _echarts = new xheCharts();

        for (let i = 0; i < _Model.tempData.length; i++) {
            if (_Model.tempData[i]["index"] == _Model.tempIndex) {

                vIndex = i;

                continue;
            }
        }

        _model.options = _Model.tempData[vIndex].model.options;
        _echarts.options = _Model.tempData[vIndex].echart.options;

        _model.set();
        _model.load();

        _echarts.set();

        if (_echarts.options.type != eCharts.type.Export) {
            _echarts.load();
        }

        let vEventIndex = -1;

        if (_IntervalList != null && _IntervalList != undefined && _IntervalList.length > 0) {

            for (let i = 0; i < _IntervalList.length; i++) {

                if (_IntervalList[i]["key"] == _echarts.options.control) {

                    try {
                        clearInterval(_IntervalList[i]["event"]);
                    }
                    catch (e) {
                        alert(e);
                    }
                }
            }
        }

        if (vEventIndex != -1) {

            delete _IntervalList.splice(vEventIndex, 1);
        }

        if (_echarts.options.searchModel != undefined
            && _echarts.options.searchModel.period != undefined
            && _echarts.options.searchModel.period != "undefined"
            && _echarts.options.searchModel.period != 0) {
            alert(_echarts.options.searchModel.period);
            let vTimer = setInterval("intervalMethod('" + JSON.stringify(_echarts.options) + "')", Number(_echarts.options.searchModel.period) * 1000);

            _IntervalList.push({ "key": _echarts.options.control, "event": vTimer });
        }

        document.getElementById("spn_model_" + _Model.tempIndex).innerHTML = JSON.stringify(_model.options);
        document.getElementById("spn_echarts_" + _Model.tempIndex).innerHTML = JSON.stringify(_echarts.options);

    }
    catch (e) {
        alert(e)
    }
}

//事件：保存按钮
function save(type) {
    try {

        // var data = GZip.compress(JSON.stringify(_Model.tempData));

        // console.log(encodeURIComponent(data));
        // console.log("压缩前长度：" + JSON.stringify(_Model.tempData).length + "，压缩后长度：" + data.length);

        // var unData = GZip.decompress(data);

        // console.log("解压后文字：" + unData + "，解压后长度：" + unData.length);

        let xheList = new XheList();

        xheList.model.ModalID = "div_Save";

        if (type == "save") {

            xheList.model.Table = "t_data_view";
            xheList.model.ClassName = "temp_save";
            if (_isView) {
                xheList.model.PrimaryKey = 'viewid';
                xheList.edit();
            }
            else {
                xheList.add();
            }
        }
        else if (type == "template") {

            xheList.model.Table = "t_data_template";
            xheList.model.ClassName = "temp_template";
            if (_isTemplate) {

                xheList.model.PrimaryKey = 'tempid';
                xheList.edit();
            }
            else {
                xheList.add();
            }

        } if (type == "publish") {

            xheList.model.Table = "t_data_publish";
            xheList.model.ClassName = "temp_publish";
            if (_isPublish) {
                xheList.model.PrimaryKey = 'publishid';
                xheList.edit();
            }
            else {
                xheList.add();
            }
        }

        bindPanel();
        bindView();
    }
    catch (e) { }
}

//加载模块
let loadModel = function () {

    try {
        this.tempIndex = 0;
        this.tempData = new Array();


        if (_Template != undefined && _Template != null && _Template.length > 0) {
            this.tempData = _Template;
        }
        else {
            this.tempData = TEMPLAETLIST[0].value;
        }

        let options = {};
        $('#grid-stack').gridstack(options);

        this.grid = $('#grid-stack').data('gridstack');

        this.load_grid = function () {
            try {

                this.grid.remove_all();

                _.each(this.tempData, function (node) {

                    var _index = node.index;

                    let _model = new xheModel();
                    let _echarts = new xheCharts();

                    _model.options = node.model.options;
                    _echarts.options = node.echart.options;


                    if (_model.options.titleText == "") {
                        _model.options.titleText = `模块${_index}`;
                    }

                    _model.options.index = _index;
                    _echarts.options.control = "div_model_" + _index;

                    if (_echarts.options.searchControl == undefined) {
                        _echarts.options.searchControl = {
                            ID: "",
                            text: "",
                            union: "A",
                            exist: "EQ",
                            dataType: "I",
                            event: "",
                            disabled: false,
                            checkedValue: "",
                            defaultValue: "",
                            format: ""
                        };
                    }
                    if (_echarts.options.searchControl.ID == "") {
                        if (_echarts.options.type == eCharts.type.Button || _echarts.options.type == eCharts.type.Export) {
                            _echarts.options.searchControl.ID = "btn_" + _index;
                        }
                        else if (_echarts.options.type == eCharts.type.Text) {
                            _echarts.options.searchControl.ID = "txt_" + _index;
                        }
                        else if (_echarts.options.type == eCharts.type.Select) {
                            _echarts.options.searchControl.ID = "ddl_" + _index;
                        }
                        else if (_echarts.options.type == eCharts.type.Date) {
                            _echarts.options.searchControl.ID = "dt_" + _index;
                        }
                        else {
                            _echarts.options.searchControl.ID = "echart_" + _index;
                        }
                    }

                    let vTemplate = `
                    <div id="div_main_${_index}">
                        <div id="div_content_${_index}" class="grid-stack-item-content boxall" style="overflow-y: hidden;">
                            <div id="div_config_${_index}" class="grid-stack-config" onmouseout="showConfig(${_index},false)" onmouseover="showConfig(${_index},true)">
                                <div id="remove-grid-${_index}" index="${_index}" x="${node.x}" y="${node.y}" class="icon-remove div-stack-config-remove">
                                    <i class='glyphicon glyphicon-remove' style="font-size:12px; margin-top: 0.3vh; color:#a7a4a4"></i>
                                </div>
                                <div id="config-grid-${_index}" index="${_index}" class="icon-config div-stack-config-cog">
                                    <i class='glyphicon glyphicon-cog' style="font-size:12px; margin-top: 0.3vh; color:#a7a4a4"></i>
                                </div>
                                <span id="spn_model_${_index}" style="display:none;">${JSON.stringify(_model.options)}</span>
                                <span id="spn_echarts_${_index}" style="display:none;">${JSON.stringify(_echarts.options)}</span>
                            </div>
                            <h1 id="h_head_${_index}" class="grid-stack-item-tl">
                                <div id="div_head_${_index}" class="grid-stack-item-dv">                                     
                                    <span>&nbsp;&nbsp;</span>
                                    <span id="spn_title_${_index}" class="grid-stack-item-sp"></span>                                
                                </div>        
                            </h1>
                            <div id="div_model_${_index}" class="grid-stack-item-nr"></div>
                            <div id="div_foot_${_index}" class="boxfoot"></div>
                        </div>
                    </div>`;

                    this.grid.add_widget($(vTemplate), node.x, node.y, node.width, node.height, undefined, node.index);
                    //console.log(_model.options.titleText + " x:" + node.x + " y:" + node.y);
                    $('#remove-grid-' + _index).click(this.remove_grid);
                    $('#config-grid-' + _index).click(this.config_grid);

                    // alert(_model.options.titleText);
                    // alert(_model.options.index);
                    // alert(_echarts.options.control);


                    _model.load();

                    if (_echarts.options.type == eCharts.type.Button
                        || _echarts.options.type == eCharts.type.Text
                        || _echarts.options.type == eCharts.type.Select
                        || _echarts.options.type == eCharts.type.Date) {

                        _echarts.load();
                    } else if (_echarts.options.type == eCharts.type.Export) {
                        _echarts.loadEx();
                    }

                    // if (_echarts.options.type == eCharts.type.Button) {
                    //     _ButtonList.push(_echarts.options.searchControl);
                    // }

                    // if (_echarts.options.searchModel != undefined && _echarts.options.searchModel.period != undefined && _echarts.options.searchModel.period != 0) {

                    //     _IntervalList.push(_echarts);
                    // }

                    //$('#div_main_' + _index).find(".ui-resizable-handle").mouseup(function () { setTimeout("gridStackMoveEvent(" + _index + ")", 300); });


                    $('#div_main_' + _index).find(".ui-resizable-handle").on('mouseup', () => { setTimeout("gridStackMoveEvent(" + _index + ")", 300); });

                    //_echarts.load();

                    // _Template[_index - 1].model = _model;
                    // _Template[_index - 1].echart = _echarts;


                }, this);
            }
            catch (e) {
                alert(e)
            }
        }.bind(this);

        this.save_grid = function () {

            this.tempData = _.map($('.grid-stack > .grid-stack-item:visible'), function (el) {
                el = $(el);

                var node = el.data('_gridstack_node');
                let _model = new xheModel();
                let _echarts = new xheCharts();

                _model.options = JSON.parse(document.getElementById("spn_model_" + node.index).innerHTML);
                _echarts.options = JSON.parse(document.getElementById("spn_echarts_" + node.index).innerHTML);

                return {
                    index: node.index,
                    x: node.x,
                    y: node.y,
                    width: node.width,
                    height: node.height,
                    model: _model,
                    echart: _echarts
                };
            }, this);

            $('#saved-data').val(JSON.stringify(this.tempData, null, '    '));
        }.bind(this);

        this.clear_grid = function () {
            this.grid.remove_all();
        }.bind(this);

        this.inner_grid = function () {
            $("#saved-data").val(document.getElementById("grid-stack").innerHTML);

        }.bind(this);

        this.add_grid = function (o) {

            this.save_grid();

            var vWidth = 3;
            var vHeight = 5;
            var vModel = new xheModel();
            var vEchart;

            switch (o) {
                case 'label':
                    vModel = initLabelModel();
                    vEchart = initLabel();
                    break;
                case 'vbar':
                    vEchart = initVBar();
                    break;
                case 'hbar':
                    vEchart = initHBar();
                    break;
                case 'line':
                    vEchart = initLine();
                    break;
                case 'barline':
                    vEchart = initBarline();
                    break;
                case 'pie':
                    vEchart = initPie();
                    break;
                case 'gauge':
                    vEchart = initGauge();
                    break;
                case 'radar':
                    vEchart = initRadar();
                    break;
                case 'funnel':
                    vEchart = initFunnel();
                    break;
                case 'map':
                    vEchart = initMap();
                    break;
                case 'table':
                    vEchart = initTable();
                    break;
                case 'select':
                    vModel = initSelectModel();
                    vEchart = initSelect();
                    vWidth = 2;
                    vHeight = 1;
                    break;
                case 'text':
                    vModel = initTextModel();
                    vEchart = initText();
                    vWidth = 2;
                    vHeight = 1;
                    break;
                case 'button':
                    vModel = initButtonModel();
                    vEchart = initButton();
                    vWidth = 1;
                    vHeight = 1;
                    break;
                case 'export':
                    vModel = initButtonModel();
                    vEchart = initExport();
                    vWidth = 1;
                    vHeight = 1;
                    break;
                case 'date':
                    vModel = initDateModel();
                    vEchart = initDateControl();
                    vWidth = 2;
                    vHeight = 1;
                    break;
                default:
                    break;
            }

            if (vEchart == null) {
                alert("该功能未实现!");
            }
            else {
                var vIndex = 0;
                var vX = 0;
                var vY = 0;

                for (let i = 0; i < this.tempData.length; i++) {


                    if (vY <= (Number(this.tempData[i].y) + Number(this.tempData[i].height))) {
                        vY = (Number(this.tempData[i].y) + Number(this.tempData[i].height));
                    }

                    if (Number(this.tempData[i].x) + Number(this.tempData[i].width) + vWidth > 12) {
                        vX = 0;
                    }
                    else {
                        vX = Number(this.tempData[i].x) + Number(this.tempData[i].width);
                    }

                    if (vIndex <= Number(this.tempData[i].index)) {
                        vIndex = Number(this.tempData[i].index) + 1;
                    }
                }

                if (vWidth == 0) {
                    vWidth = 3;
                }

                if (vModel.options.titleText == "") {
                    vModel.options.titleText = `模块${vIndex}`;
                }

                vModel.options.index = vIndex;
                vEchart.options.control = "div_model_" + vIndex;




                if (vEchart.options.searchControl == undefined) {
                    vEchart.options.searchControl = {
                        ID: "",
                        text: "",
                        union: "A",
                        exist: "EQ",
                        dataType: "I",
                        event: "",
                        disabled: false,
                        checkedValue: "",
                        defaultValue: "",
                        format: ""
                    };
                }


                if (vEchart.options.searchControl.ID == "") {
                    if (vEchart.options.type == eCharts.type.Button || vEchart.options.type == eCharts.type.Export) {
                        vEchart.options.searchControl.ID = "btn_" + vIndex;
                    }
                    else if (vEchart.options.type == eCharts.type.Text) {
                        vEchart.options.searchControl.ID = "txt_" + vIndex;
                    }
                    else if (vEchart.options.type == eCharts.type.Select) {
                        vEchart.options.searchControl.ID = "ddl_" + vIndex;
                    }
                    else if (vEchart.options.type == eCharts.type.Date) {
                        vEchart.options.searchControl.ID = "dt_" + vIndex;
                    }
                    else {
                        vEchart.options.searchControl.ID = "echart_" + vIndex;
                    }
                }



                let vTemplate = `
                    <div id="div_main_${vIndex}">
                        <div id="div_content_${vIndex}" class="grid-stack-item-content boxall" style="overflow-y: hidden;">
                            <div id="div_config_${vIndex}" class="grid-stack-config" onmouseout="showConfig(${vIndex},false)" onmouseover="showConfig(${vIndex},true)">
                                <div id="remove-grid-${vIndex}" index="${vIndex}" x="${vX}" y="${vY}" class="icon-remove div-stack-config-remove">
                                    <i class='glyphicon glyphicon-remove' style="font-size:12px; margin-top: 0.3vh; color:#a7a4a4"></i>
                                </div>
                                <div id="config-grid-${vIndex}" index="${vIndex}" class="icon-config div-stack-config-cog">
                                    <i class='glyphicon glyphicon-cog' style="font-size:12px; margin-top: 0.3vh; color:#a7a4a4"></i>
                                </div>
                                <span id="spn_model_${vIndex}" style="display:none;">${JSON.stringify(vModel.options)}</span>
                                <span id="spn_echarts_${vIndex}" style="display:none;">${JSON.stringify(vEchart.options)}</span>
                            </div>
                            <h1 id="h_head_${vIndex}" class="grid-stack-item-tl">
                                <div id="div_head_${vIndex}" class="grid-stack-item-dv">                                     
                                    <span>&nbsp;&nbsp;</span>
                                    <span id="spn_title_${vIndex}" class="grid-stack-item-sp"></span>                                
                                </div>        
                            </h1>
                            <div id="div_model_${vIndex}" class="grid-stack-item-nr"></div>
                            <div id="div_foot_${vIndex}" class="boxfoot"></div>
                        </div>
                    </div>`;

                this.grid.add_widget($(vTemplate), vX, vY, vWidth, vHeight, undefined, vIndex);

                $('#remove-grid-' + vIndex).click(this.remove_grid);
                $('#config-grid-' + vIndex).click(this.config_grid);

                // alert(_model.options.titleText);
                // alert(_model.options.index);
                // alert(_echarts.options.control);



                if (vEchart.options.type == eCharts.type.Button) {
                    _ButtonList.push(vEchart.options.searchControl);
                }

                if (vEchart.options.searchModel != undefined && vEchart.options.searchModel.period != undefined && vEchart.options.searchModel.period != 0) {

                    _IntervalList.push(vEchart);
                }

                $('#div_main_' + vIndex).find(".ui-resizable-handle").mouseup(function () { setTimeout("gridStackMoveEvent(" + vIndex + ")", 100); });



                vModel.load();

                vEchart.load();


                this.tempData.push({ index: vIndex, x: vX, y: vY, width: vWidth, height: vHeight, model: vModel, echart: vEchart });


                //this.load_grid();

                alert("添加成功!");

                closeToolBar();
            }
        }.bind(this);

        this.remove_grid = function (o) {
            try {
                this.save_grid();

                let vIndex = 0;
                let tempIndex = $("#" + o.currentTarget.id).attr("index");

                for (let i = 0; i < this.tempData.length; i++) {
                    if (this.tempData[i]["index"] == tempIndex) {

                        vIndex = i;

                        continue;
                    }
                }

                delete this.tempData.splice(vIndex, 1);

                _.map($('.grid-stack > .grid-stack-item:visible'), function (el) {


                    var node = $(el).data('_gridstack_node');

                    if (tempIndex == node.index) {

                        this.grid.remove_widget($(el));
                    }

                }, this);



                //this.load_grid();
            }
            catch (e) {
                alert(e)
            }
        }.bind(this);

        this.config_grid = function (o) {
            try {



                let vIndex = 0;
                this.tempIndex = $("#" + o.currentTarget.id).attr("index");

                let _model = new xheModel();
                let _echarts = new xheCharts();

                for (let i = 0; i < this.tempData.length; i++) {
                    if (this.tempData[i]["index"] == this.tempIndex) {

                        vIndex = i;

                        continue;
                    }
                }
                _model.options = this.tempData[vIndex].model.options;
                _echarts.options = this.tempData[vIndex].echart.options;


                var mySelect = $("#echart_bindtype option");

                if (_echarts.options.type == "VBar" || _echarts.options.type == "HBar" || _echarts.options.type == "Line" || _echarts.options.type == "Pie" || _echarts.options.type == "Table") {

                    mySelect.each(function (i, el) {
                        if ($(el).text() == "数据指标") {
                            $(this).show();
                        }
                    });

                    if (_echarts.options.type == "Pie") {
                        document.getElementById("div_quotaindex").innerHTML = '<select id="echart_quotaindex" name="" class="selectpicker form-control con-none"></select>';
                    }
                    else {
                        document.getElementById("div_quotaindex").innerHTML = '<select id="echart_quotaindex" name="" multiple class="selectpicker form-control con-none"></select>';
                    }

                    if (_echarts.options.type == "Table") {
                        document.getElementById("div_quotasecondcategory").style.display = "block";
                    }
                    else {
                        document.getElementById("div_quotasecondcategory").style.display = "none";
                        document.getElementById("div_quotasecondcategory").value = "";
                    }
                }
                else {
                    mySelect.each(function (i, el) {
                        if ($(el).text() == "数据指标") {
                            $(this).hide();
                        }
                    });
                }



                _model.bind();
                _echarts.bind();

                changeBindType(_echarts.options.type);

                $("#div_Modal").modal("show");
            }
            catch (e) {
                alert(e)
            }
        }.bind(this);

        this.load_area = function () {
            loadArea(this.tempData);
        }

        this.load_grid();

        $('#save-grid').click(this.save_grid);
        $('#load-grid').click(this.load_grid);
        $('#clear-grid').click(this.clear_grid);
        $('#inner-grid').click(this.inner_grid);

        //$('.a_add_panel').click($(this).attr("name"), this.load_grid);
    }
    catch {
        alert(e);
    }
};

//更换背景
function changeBackGround() {
    try {
        document.getElementById("txt_viewbackground").value = document.getElementById("ddl_view_backGround").options[document.getElementById("ddl_view_backGround").selectedIndex].value;
        document.getElementById("txt_tempbackground").value = document.getElementById("ddl_view_backGround").options[document.getElementById("ddl_view_backGround").selectedIndex].value;
        document.getElementById("txt_publishbackground").value = document.getElementById("ddl_view_backGround").options[document.getElementById("ddl_view_backGround").selectedIndex].value;
        document.getElementById("div_background").style.backgroundImage = "url(../../common/imgs/" + document.getElementById("ddl_view_backGround").options[document.getElementById("ddl_view_backGround").selectedIndex].value + ")";
    }
    catch (e) {
        alert(e);
    }
}

//绑定模板
function bindPanel() {
    try {
        document.getElementById("AddPanel").innerHTML = "";

        TEMPLAETLIST = new Array();
        TEMPLAETLIST.push({ key: "空白模板", value: [{ index: 0, x: 0, y: 0, width: 12, height: 2, model: initTitleModel(), echart: initTitle() }] });

        //查询模板
        let xheList = new XheList();
        //_SearchModel.Methed = "DataCenterGet_1_0";
        xheList.model.Table = "t_data_template";
        xheList.model.SortName = "tempid";

        xheList.model.Columns = [
            ["tempid", "模板ID", "15", "", "I", "", true],
            ["tempname", "模板名称", "15", "", "C", "", true]
        ];

        xheList.model.Filter = [
            ["tempstatus", "A", "EQ", "I", 1]
        ];

        let vResult = xheList.query();

        //添加模板
        if (vResult != undefined && vResult != null && vResult.rows != null) {
            for (let i = 0; i < vResult.rows.length; i++) {

                //TEMPLAETLIST.push({ id: vResult.rows[i]["tempid"], key: vResult.rows[i]["tempname"], value: JSON.parse(GZip.decompress(decodeURIComponent(String(vResult.rows[i]["tempcode"]).replace(/&apos/g, "'")))) })
                TEMPLAETLIST.push({ id: vResult.rows[i]["tempid"], key: vResult.rows[i]["tempname"] })
            }
        }

        //输出模板
        for (let i = 0; i < TEMPLAETLIST.length; i++) {
            document.getElementById("AddPanel").innerHTML += `
                <li>
                    <a href='#' class='nav-header collapsed' data-toggle='collapse' onclick='showPanel(` + TEMPLAETLIST[i].id + `);'>
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class="glyphicon glyphicon-file"></i>&nbsp;`+ TEMPLAETLIST[i].key + `
                    </a>
                </li>
            `;
        }
    }
    catch (e) {

    }
}

//显示模板
function showPanel(id) {
    try {

        for (let i = 0; i < TEMPLAETLIST.length; i++) {
            if (TEMPLAETLIST[i].id == id) {

                //_Template = TEMPLAETLIST[i].value;

                //查询模板
                let xheList = new XheList();
                xheList.model.Table = "t_data_template";
                xheList.model.SortName = "tempid";

                xheList.model.Columns = [
                    ["tempcode", "模板代码", "15", "", "C", "", true]
                ];

                xheList.model.Filter = [
                    ["tempid", "A", "EQ", "I", id]
                ];

                let vResult = xheList.query();

                if (vResult != undefined && vResult != null && vResult.rows != null) {

                    _Template = JSON.parse(GZip.decompress(decodeURIComponent(String(vResult.rows[0]["tempcode"]).replace(/&apos/g, "'"))));

                }

                break;
            }
        }

        closeToolBar();

        _Model = new loadModel();

        loadMethod();
    }
    catch (e) {
        alert(e);
    }
}

//绑定视图
function bindView() {
    try {

        document.getElementById("MyView").innerHTML = "";

        _View = new Array();

        //查询模板
        let xheList = new XheList();
        //_SearchModel.Methed = "DataCenterGet_1_0";
        xheList.model.Table = "t_data_view";
        xheList.model.SortName = "viewid";
        xheList.model.SortOrder = "desc";

        xheList.model.Columns = [
            ["viewid", "视图ID", "15", "", "C", "", true],
            ["viewname", "视图名称", "15", "", "C", "", true],
            ["viewcode", "视图代码", "15", "", "C", "", true],
            ["viewremark", "视图描述", "50", "", "C", "", true],
            ["viewbackground", "背景图", "50", "", "C", "", true]
        ];

        xheList.model.Filter = [
            ["viewuserid", "A", "EQ", "C", USER_INFO.AppID]
        ];

        let vResult = xheList.query();

        //添加视图
        if (vResult != undefined && vResult != null && vResult.rows != null) {
            for (let i = 0; i < vResult.rows.length; i++) {

                //_View.push({ id: vResult.rows[i]["viewid"], name: vResult.rows[i]["viewname"], code: JSON.parse(GZip.decompress(decodeURIComponent(String(vResult.rows[i]["viewcode"]).replace(/&apos/g, "'")))), remark: vResult.rows[i]["viewremark"] });
                //_View.push({ id: vResult.rows[i]["viewid"], name: vResult.rows[i]["viewname"], code: vResult.rows[i]["viewcode"], remark: vResult.rows[i]["viewremark"], background: vResult.rows[i]["viewbackground"] });
                _View.push({ id: vResult.rows[i]["viewid"], name: vResult.rows[i]["viewname"], remark: vResult.rows[i]["viewremark"], background: vResult.rows[i]["viewbackground"] });
            }
        }

        //输出视图
        for (let i = 0; i < _View.length; i++) {
            document.getElementById("MyView").innerHTML += `
                <li>
                    <a href='#' class='nav-header collapsed' data-toggle='collapse' onclick='showMyView(` + _View[i].id + `);'>
                        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<i class="glyphicon glyphicon-credit-card"></i>&nbsp;`+ _View[i].name + `
                    </a>
                </li>
            `;
        }


    }
    catch (e) {
        alert(e);
    }
}

//显示视图
function showMyView(id) {
    try {

        for (let i = 0; i < _View.length; i++) {
            if (_View[i].id == id) {

                //查询模板
                let xheList = new XheList();
                //_SearchModel.Methed = "DataCenterGet_1_0";
                xheList.model.Table = "t_data_view";
                xheList.model.SortName = "viewid";
                xheList.model.SortOrder = "desc";

                xheList.model.Columns = [
                    ["viewcode", "视图代码", "15", "", "C", "", true]
                ];

                xheList.model.Filter = [
                    ["viewid", "A", "EQ", "I", id]
                ];

                let vResult = xheList.query();

                //添加视图
                if (vResult != undefined && vResult != null && vResult.rows != null) {

                    _Template = JSON.parse(GZip.decompress(decodeURIComponent(String(vResult.rows[0]["viewcode"]).replace(/&apos/g, "'"))));

                    $("#txt_PK_Value").val(_View[i].id);
                    $("#txt_viewname").val(_View[i].name);
                    $("#txt_viewname").attr("disabled", true);
                    $("#txt_viewremark").val(_View[i].remark);

                    if (_View[i].background != "") {
                        $("#txt_viewbackground").val(_View[i].background);
                        $("#txt_tempbackground").val(_View[i].background);
                        $("#txt_publishbackground").val(_View[i].background);
                        document.getElementById("div_background").style.backgroundImage = "url(../../common/imgs/" + _View[i].background + ")";
                    }
                }

                break;
            }
        }

        closeToolBar();

        _Model = new loadModel();

        loadMethod();

        _isView = true;

    }
    catch (e) {
        alert(e);
    }
}

//显示功能管理
function showSave(type) {
    try {
        _Model.save_grid();

        if (!_isView && !_isTemplate && !_isPublish) {
            document.getElementById("txt_PK_Value").value = "";
        }

        if (!_isView) {
            document.getElementById("txt_viewname").value = "";
            document.getElementById("txt_viewremark").value = "";
            $("#txt_viewname").attr("disabled", false);
        }

        if (!_isTemplate) {
            document.getElementById("txt_tempname").value = "";
            document.getElementById("txt_tempremark").value = "";
            $("#txt_tempname").attr("disabled", false);
        }

        if (!_isPublish) {
            document.getElementById("txt_publishname").value = "";
            document.getElementById("txt_publishremark").value = "";
            $("#txt_publishname").attr("disabled", false);
        }

        if (type == "save") {

            document.getElementById("txt_viewuserid").value = USER_INFO.AppID;
            document.getElementById("txt_viewusername").value = USER_INFO.RealName;
            document.getElementById("txt_viewcode").value = String(encodeURIComponent(GZip.compress(JSON.stringify(_Model.tempData)))).replace(/'/g, "&apos");
        }
        else if (type == "template") {

            document.getElementById("txt_tempstatus").value = 1;
            document.getElementById("txt_tempuserid").value = USER_INFO.AppID;
            document.getElementById("txt_tempusername").value = USER_INFO.RealName;
            document.getElementById("txt_tempcode").value = String(encodeURIComponent(GZip.compress(JSON.stringify(_Model.tempData)))).replace(/'/g, "&apos");

        } if (type == "publish") {

            document.getElementById("txt_publishstatus").value = 1;
            document.getElementById("txt_publishuserid").value = USER_INFO.AppID;
            document.getElementById("txt_publishusername").value = USER_INFO.RealName;
            document.getElementById("txt_publishcode").value = String(encodeURIComponent(GZip.compress(JSON.stringify(_Model.tempData)))).replace(/'/g, "&apos");
        }

        document.getElementById("btn_save").value = type;
        document.getElementById("div_modal_save").style.display = "none";
        document.getElementById("div_modal_template").style.display = "none";
        document.getElementById("div_modal_publish").style.display = "none";
        document.getElementById("div_modal_" + type).style.display = "block";
        $("#div_Save").modal("show");
    }
    catch (e) {
        //alert(e);
    }
}

//跳转到发布管理
function showPublish() {
    try {
        jumpUrl("UI-FBGL", USER_INFO.AppID);
    }
    catch (e) { }
}

//显示模块上的编辑与删除按钮
function showConfig(index, type) {

    try {
        if (type) {
            document.getElementById("remove-grid-" + index).style.display = "block";
            document.getElementById("config-grid-" + index).style.display = "block";
        }
        else {
            document.getElementById("remove-grid-" + index).style.display = "none";
            document.getElementById("config-grid-" + index).style.display = "none";
        }
    }
    catch (e) {
        alert(e)
    }
}

//切换整体主题
function changeAllTheme() {
    try {
        _Model.save_grid();

        let themeKey = document.getElementById("ddl_view_theme").value;

        for (let i = 0; i < _Model.tempData.length; i++) {

            for (let j = 0; j < eCharts.theme.length; j++) {
                if (themeKey == eCharts.theme[j].key) {
                    _Model.tempData[i].echart.options.colorTheme = eCharts.theme[j];
                    break;
                }
            }

        }

        _Model.load_grid();

        loadMethod();
    }
    catch (e) { }
}

//切换数据绑定方式
function changeBindType(type) {

    try {

        let bindType = document.getElementById("echart_bindtype").value;

        document.getElementById("div_bindtype_server").style.display = "none";
        document.getElementById("div_bindtype_data").style.display = "none";
        document.getElementById("div_bindtype_quota").style.display = "none";

        if (bindType != "") {
            document.getElementById("div_bindtype_" + bindType).style.display = "block";

            if (bindType == "quota") {
                queryQuotaList(document.getElementById("echart_quotavalue").name);

                if (document.getElementById("echart_quotaindex").name != "") {
                    queryQuotaIndex(document.getElementById("echart_quotaindex").name);
                }
                else {
                    OptionUtil.bind("echart_quotaindex", "name", "value", [], false, "", null);
                }

                if (document.getElementById("echart_quotacategory").name != "") {
                    queryQuotaCategory(document.getElementById("echart_quotacategory").name);
                }
                else {
                    OptionUtil.bind("echart_quotacategory", "name", "value", [], false, "", null);
                }

                if (type == "Table") {
                    if (document.getElementById("echart_quotasecondcategory").name != "") {
                        queryQuotaSecondCategory(document.getElementById("echart_quotasecondcategory").name);
                    }
                    else {
                        OptionUtil.bind("echart_quotasecondcategory", "name", "value", [], false, "", null);
                    }
                }
            }
        }
    }
    catch (e) { }
}

//查询指标体系
function queryQuotaList(value) {
    try {

        if (value == undefined) {
            value = "";
        }

        var vSearch = new xheCharts();
        vSearch.options.searchModel.connection = CONNECTIONLIST[2].name;

        vSearch.options.searchModel.table = "t_zbtx_zb";
        vSearch.options.searchModel.sortName = "id";
        vSearch.options.searchModel.dataType = "Pie";
        vSearch.options.searchModel.columns = [
            ["id", "id", "I", ""],
            //["sjjid", "id", "I", ""],
            ["mc", "mc", "C", ""]
        ];
        vSearch.options.searchModel.filter = [
            ["mc", "A", "NE", "C", "EMPTY"]
        ];

        var vResult = vSearch.query();

        OptionUtil.bind("echart_quotavalue", "name", "value", vResult.data, false, value, null);
    }
    catch (e) { }
}

//查询指标
function queryQuotaIndex(value) {
    try {

        if (value == undefined) {
            value = "";
        }

        let vQuotaID = document.getElementById("echart_quotavalue").value;

        var vSearch = new xheCharts();
        vSearch.options.searchModel.connection = CONNECTIONLIST[2].name;
        vSearch.options.searchModel.table = "zb";
        vSearch.options.searchModel.sortName = "id";
        vSearch.options.searchModel.dataType = "Pie";
        vSearch.options.searchModel.columns = [
            ["zdid", "id", "I", ""],
            ["zbmc", "mc", "C", ""]
        ];
        vSearch.options.searchModel.filter = [
            ["zbsid", "A", "EQ", "I", vQuotaID]
        ];

        var vResult = vSearch.query();

        OptionUtil.bind("echart_quotaindex", "name", "value", vResult.data, false, value, null);
    }
    catch (e) { }
}

//查询分类
function queryQuotaCategory(value) {
    try {

        if (value == undefined) {
            value = "";
        }

        let vQuotaID = document.getElementById("echart_quotavalue").value;

        var vSearch = new xheCharts();
        vSearch.options.searchModel.connection = CONNECTIONLIST[2].name;

        vSearch.options.searchModel.table = "flmx";
        vSearch.options.searchModel.sortName = "flmc";
        vSearch.options.searchModel.dataType = "Pie";
        vSearch.options.searchModel.columns = [
            ["flzd", "flzd", "I", ""],
            ["flmc", "flmc", "C", ""]
        ];
        vSearch.options.searchModel.filter = [
            ["zbsid", "A", "EQ", "I", vQuotaID]
        ];

        var vResult = vSearch.query();

        OptionUtil.bind("echart_quotacategory", "name", "value", vResult.data, false, value, null);
    }
    catch (e) { }
}

//查询二级分类
function queryQuotaSecondCategory(value) {
    try {

        if (value == undefined) {
            value = "";
        }

        let vQuotaID = document.getElementById("echart_quotavalue").value;

        var vSearch = new xheCharts();
        vSearch.options.searchModel.connection = CONNECTIONLIST[2].name;

        vSearch.options.searchModel.table = "flmx";
        vSearch.options.searchModel.sortName = "flmc";
        vSearch.options.searchModel.dataType = "Pie";
        vSearch.options.searchModel.columns = [
            ["flzd", "flzd", "I", ""],
            ["flmc", "flmc", "C", ""]
        ];
        vSearch.options.searchModel.filter = [
            ["zbsid", "A", "EQ", "I", vQuotaID]
        ];

        var vResult = vSearch.query();

        OptionUtil.bind("echart_quotasecondcategory", "name", "value", vResult.data, false, value, null);
    }
    catch (e) { }
}

//单个按钮加载事件
function searchMethod(params) {

    try {

        if (String(params.event).indexOf("url:") > -1) {

            let url = "";
            let permission = "";

            if (String(params.event).indexOf("|") > -1) {

                url = String(params.event).split('|')[0].replace("url:", "").replaceAll("&amp;", "&").replace("{qxcode}", USER_INFO.OrganizeCode);
                permission = String(params.event).split('|')[1];
            }
            else {
                url = params.event.replace("url:", "").replaceAll("&amp;", "&").replace("{qxcode}", USER_INFO.OrganizeCode);
            }

            let aryUrlItem = url.split("{");

            url = "";

            for (let i = 0; i < aryUrlItem.length; i++) {

                if (aryUrlItem[i].indexOf("}") > -1) {
                    let controlID = "";
                    let format = "";

                    let params = aryUrlItem[i].split("}")[0]

                    if (params.indexOf(",") > -1) {
                        controlID = params.split(",")[0];
                        format = params.split(",")[1];
                    }
                    else {
                        controlID = params;
                    }

                    if (document.getElementById(controlID) != undefined && document.getElementById(controlID) != null) {
                        if (format != "") {
                            url += document.getElementById(controlID).value.replace(format, "") + aryUrlItem[i].split("}")[1];
                        }
                        else {
                            url += document.getElementById(controlID).value + aryUrlItem[i].split("}")[1];
                        }
                    }
                    else {
                        url += "{" + aryUrlItem[i];
                    }
                }
                else {
                    url += aryUrlItem[i];
                }
            }

            if (permission == "") {
                window.open(url);
            }
            else {

                if (judgeMatch(permission)) {

                    window.open(url);
                }
                else {

                    alert("没有权限!");
                }
            }
        }
        else {
            for (let i = 0; i < _Model.tempData.length; i++) {


                if (_Model.tempData[i].echart.options.searchControl != undefined) {

                    if (String(params.event + "|").indexOf(String(_Model.tempData[i].echart.options.searchControl.ID) + "|") > -1) {
                        var echart = new xheCharts();
                        echart.options = _Model.tempData[i].echart.options;
                        echart.load();
                    }
                }
            }
        }



    }
    catch (e) {
        alert(e);
    }
}

//单个按钮加载事件
function exportMethod(params) {

    try {
        var echart = new xheCharts();
        echart.options = params;
        echart.load();




        let vHtml = "<tr>";

        for (let i = 0; i < params.searchModel.columns.length; i++) {

            vHtml += "<td>" + params.searchModel.columns[i][1] + "</td>"
        }

        vHtml += "</tr>"

        for (let i = 0; i < params.data.length; i++) {

            vHtml += "<tr>";


            for (let j = 0; j < params.searchModel.columns.length; j++) {

                vHtml += "<td>" + params.data[i][params.searchModel.columns[j][0]] + "</td>"
            }

            vHtml += "</tr>"
        }

        document.getElementById("export_" + params.searchControl.ID).innerHTML = vHtml;

        alert(params.data.length)

        //exceltable为存放数据的table
        $("#export_" + params.searchControl.ID).table2excel({
            // 不被导出的表格行的CSS class类
            exclude: ".noExl",
            // 导出的Excel文档的名称
            name: new Date().getTime(),
            // Excel文件的名称
            filename: new Date().getTime(),
            bootstrap: false
        });
    }
    catch (e) {
        alert(e);
    }
}

//所有按钮加载事件
function loadMethod() {
    try {

        for (let i = 0; i < _Model.tempData.length; i++) {

            if (_Model.tempData[i].echart.options.type != eCharts.type.Button
                && _Model.tempData[i].echart.options.type != eCharts.type.Text
                && _Model.tempData[i].echart.options.type != eCharts.type.Select
                && _Model.tempData[i].echart.options.type != eCharts.type.Date
                && _Model.tempData[i].echart.options.type != eCharts.type.Export) {

                var echart = new xheCharts();
                echart.options = _Model.tempData[i].echart.options;
                echart.load();
            }

            if (_Model.tempData[i].echart.options.searchModel != undefined
                && _Model.tempData[i].echart.options.searchModel.period != undefined
                && _Model.tempData[i].echart.options.searchModel.period != 0) {

                let vTimer = setInterval("intervalMethod('" + JSON.stringify(_Model.tempData[i].echart.options) + "')", Number(_Model.tempData[i].echart.options.searchModel.period) * 1000);

                _IntervalList.push({ "key": _Model.tempData[i].echart.options.control, "event": vTimer });
            }
        }


    }
    catch (e) {

    }
}

//调整模块大小时自动刷新echart控件
function gridStackMoveEvent(index) {
    try {

        let _echarts = new xheCharts();

        for (let i = 0; i < _Model.tempData.length; i++) {

            if (_Model.tempData[i].index == index) {

                _echarts.options = _Model.tempData[i].echart.options;

                _echarts.load();

                break;
            }
        }
    }
    catch (e) { }
}

//自动刷新的方法
function intervalMethod(options) {
    try {

        var echart = new xheCharts();
        echart.options = JSON.parse(options);
        echart.load();
    }
    catch (e) {

    }
}

//echart控件单击事件
function echartOnclick(params, options) {
    try {


        if (options.searchControl != undefined && options.searchControl.event != undefined && options.searchControl.event != "") {

            if (String(options.searchControl.event).indexOf("url:") > -1) {

                let vUrl = String(options.searchControl.event).replace("url:", "");
                let vParams = { name: params.name };

                HttpUtil.setUrlParams(vUrl, vParams);
            }
            else {
                for (let i = 0; i < _Model.tempData.length; i++) {
                    if (_Model.tempData[i].echart.options.searchControl != undefined && String(options.searchControl.event + "|").indexOf(String(_Model.tempData[i].echart.options.searchControl.ID) + "|") > -1) {

                        var echart = new xheCharts();
                        echart.options = _Model.tempData[i].echart.options;

                        for (let i = 0; i < echart.searchModel.filter.length; i++) {

                            if (String(echart.searchModel.filter[i][4] + "|").indexOf(options.searchControl.ID + "|") > -1) {

                                let vItem = new Array();
                                vItem[0] = this.options.searchModel.filter[i][0];
                                vItem[1] = this.options.searchModel.filter[i][1];
                                vItem[2] = this.options.searchModel.filter[i][2];
                                vItem[3] = this.options.searchModel.filter[i][3];
                                vItem[4] = params.name;

                                this.options.searchModel.realFilter.push(vItem);

                                echart.load();

                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    catch (e) {

    }
}


